package com.xiaohai.filter;


import com.alibaba.fastjson.JSON;
import com.xiaohai.common.GetContext;
import com.xiaohai.common.R;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;

import java.io.IOException;

/**
 * ClassName:LoginCheckFilter
 * Package:IntelliJ IDEA
 * Description:
 * Author 何诗海
 *
 * @Create 2024/1/15 14:37
 * @Version 1.0
 */
@Slf4j
@WebFilter(urlPatterns = "/*")
public class LoginCheckFilter implements Filter {


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        // 1 获取请求路径
        String uri = request.getRequestURI();

        log.info("url:{}", uri);
        log.info("id:{}", request.getSession().getAttribute("employee"));

        // 2 定义不需要拦截的枯竭
        String[] urls = {
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/images/**",
        };

        if (isChecked(uri, urls)) {
            filterChain.doFilter(request, response);
            return;
        }

        // 3 判断是否登录
        if (ObjectUtils.isEmpty(request.getSession().getAttribute("employee"))) {
            response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
            return;
        }
        GetContext.setThread((Long) request.getSession().getAttribute("employee"));

        filterChain.doFilter(request, response);
    }

    /**
     * 路径匹配器
     *
     * @param uri
     * @param urls
     * @return
     */
    private boolean isChecked(String uri, String[] urls) {
        for (String s : urls) {
            if (s.contains(uri)) {
                return true;
            }
        }
        return false;
    }


}
